const list = document.querySelector('#list'),
      $showPageImg = document.querySelector("#showPageImg"),
      btns = document.querySelector('#btns');

var imgPageList= [];
var count = 0;
var newCount = 0;
var num = 0;//记录实际分页数目

//点击删除图片
const delPic = (id,page) =>{
  let li = document.getElementById(id);
  list.removeChild(li);
  fetch(`http://192.168.142.166:8080/pictures/${id}`,{method:'delete'})
    .then(res=>res.json)
    .then(res=>{
      fetch('http://192.168.142.166:8080/pictures/getCount').then(res=>res.json())
        .then(res=>{
          newCount = res.count;
          //删除后自动补上下一个图片 
          showPage(page,newCount);
          let newNum = Math.ceil(newCount / 10);
          //页面为空时,删除空页按钮
          if(num !== newNum){
            //删除后若为空页面跳转到上一页
            if(page===num){
              showPage(num-1,newCount);
            }
            let btn = document.getElementById(`page${num}`);
            btns.removeChild(btn);
            num = num-1;
          }
      })
    })
}

//显示图片列表
const showPagePic = (picPageList,page)=>{
  list.innerHTML='';
  for(let item of picPageList){
    const li = document.createElement("li");
    li.innerHTML = ` 
      <img src='${item.src}'/>
      <p>${item.name}</p>
    `;
    const btn = document.createElement("button");
    btn.innerHTML = '删除图片';
    li.id = item.id;
    li.className = 'imgli';
    btn.className = 'delbtn';  
    btn.onclick = ()=>delPic(item.id,page);
    li.appendChild(btn);
    list.appendChild(li);
  }
}

//发起页面请求
const showPage = (page,count)=>{
  if(count>0){
    let btns = document.getElementsByClassName('showPageBtn');
    for(let i=0;i<btns.length;i++){
      btns[i].style.backgroundColor='';     
    }
    let nowBtn = document.getElementById(`page${page}`);
    nowBtn.style.backgroundColor='rgb(254, 228, 188)';
  }
  let limit = 10;
  if(page>0){
    fetch(`http://192.168.142.166:8080/pictures/showPage/?page=${page}&limit=${limit}`)
      .then(res=>res.json())
      .then(res=>{
        imgPageList = res.data
        showPagePic(imgPageList,page);
      })
  }
}

//创建页码
const show = (count)=>{
  btns.innerHTML='';
  num = Math.ceil(count / 10);
  for(let i=0;i<num;i++){
    let btn = document.createElement('button');
    btn.innerHTML = i+1;
    btn.className = 'showPageBtn';
    btn.id = `page${i+1}`;
    btn.onclick = ()=>showPage(i+1,count)
    btns.appendChild(btn)
  }
  showPage(1,count);
}

//点击获取页数
$showPageImg.onclick = ()=>{
  fetch('http://192.168.142.166:8080/pictures/getCount').then(res=>res.json())
    .then(res=>{
      count = res.count;
      show(count);
  })
}

